/* Jquery plugin START */
/*
* 表单验证，通过给需要验证的输入控件（input、select等）添加类实现验证规则设定
*
* 类名格式：mccms-validate-验证规则[?参数]
* 如：
* 非空 mccms-validate-required
* 最大长度10字符 mccms-validate-maxlength?10
* 输入值大于1小于10范围内 mccms-validate-range?[1,10]
* */
(function ($) {
    if (!$.setCookie) {
        $.extend({
            setCookie: function (c_name, value, exdays) {
                try {
                    if (!c_name) return false;
                    var exdate = new Date();
                    exdate.setDate(exdate.getDate() + exdays);
                    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
                    document.cookie = c_name + "=" + c_value;
                }
                catch (err) {
                    return '';
                };
                return '';
            }
        });
    };
    if (!$.getCookie) {
        $.extend({
            getCookie: function (c_name) {
                try {
                    var i, x, y,
                        ARRcookies = document.cookie.split(";");
                    for (i = 0; i < ARRcookies.length; i++) {
                        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                        x = x.replace(/^\s+|\s+$/g, "");
                        if (x == c_name) return (y);
                    };
                }
                catch (err) {
                    return '';
                };
                return '';
            }
        });
    };
})(jQuery);
$.fn.mcFormValide = function(options) {
    var defaultOptions = {};

    options = $.extend(defaultOptions, options);

    return this.each(function(){
        var self = $(this);

        // 需要验证的空间元素，包含mccms-validate-*类的空间元素
        var inputEles = self.find('[class*="mccms-validate-"]');

        var rules = {};
        for(var i = 0; i < inputEles.length; i++){
            var inputEle = inputEles.eq(i);
            var inputClassList = inputEles[i].classList;

            var rule = {};
            var regExpPrefix = /^mccms-validate-/;  // 前缀
            var regExpSuffix = /\?\S+$/;  // 后缀
            for(var j = 0; j < inputClassList.length; j++){
                var clazz = inputClassList[j];

                var ruleName = clazz.replace(regExpPrefix, '').replace(regExpSuffix, "");

                if(regExpPrefix.test(clazz)){
                    // 规则带参数
                    if(regExpSuffix.test(clazz)){
                        rule[ruleName] = clazz.match(regExpSuffix)[0].replace("?", "");  // 把”？“去掉
                    }
                    // 不带参数直接给true
                    else{
                        rule[ruleName] = true;
                    }
                }
            }

            rules[inputEle.attr('name')] = rule;
        }

        self.validate({
            onsubmit:false,
            errorClass : 'error-lab',
            errorElement: "span",
            rules: rules
        });
    });
};

jQuery.validator.addMethod("stringCheck", function(value, element) { 
    var reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    return this.optional(element) || reg.test(value);    
}, "只包括中文字、英文字母、数字和下划线,不能以下划线开头结尾"); 

// 自定义验证提示 
$.extend($.validator.messages, {
    required: "*必填字段",
    remote: "请修正该字段",
    email: "请输入正确格式的电子邮件",
    url: "请输入合法的网址",
    date: "请输入合法的日期",
    dateISO: "请输入合法的日期 (ISO).",
    number: "请输入合法的数字",
    digits: "只能输入整数",
    creditcard: "请输入合法的信用卡号",
    equalTo: "请再次输入相同的值",
    accept: "请输入拥有合法后缀名的字符串",
    maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串"),
    minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串"),
    rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
    range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
    max: $.validator.format("请输入一个最大为 {0} 的值"),
    min: $.validator.format("请输入一个最小为 {0} 的值")
});

/* 表情选择器用Hui tab选项卡 */
jQuery.EmotionHuitab =function(tabBar,tabCon,class_name,tabEvent,i,onClickFn){
    var $tab_menu=$(tabBar);
    // 初始化操作
    $tab_menu.removeClass(class_name);
    $(tabBar).eq(i).addClass(class_name);
    $(tabCon).hide();
    $(tabCon).eq(i).show();

    $tab_menu.on(tabEvent,function(){
        $tab_menu.removeClass(class_name);
        $(this).addClass(class_name);
        var index=$tab_menu.index(this);
        $(tabCon).hide();

        if(onClickFn && $.isFunction(onClickFn)){
            onClickFn.apply(this);
        }

        $(tabCon).eq(index).show();
    });
};
/*
 * 表情选择器
 *
 * option包括以下字段：
 * inputElement：表情文字添加到
 * panelRelativeTo：表情选择器相对于该元素
 * */
$.fn.mcEmotion = function(options){
    var self = $(this);
    var bodyEle = $('body');

    // 显示表情包下所有表情 模板
    var emtionTemplate = '<div class="emotion__tab-content_emotion-wrapper">' +
                            '{{#each resultList}} ' +
                            '<img src="{{file}}" alt="demo emotion" class="emotion__tab-content__emotion-image" code="{{code}}"> ' +
                            '{{/each}}' +
                        '</div>';

    var emotionTmpContainerId = 'emotionTmpContainer';

    if(!options.tempContainer || options.tempContainer.length <= 0){
        bodyEle.append('<div class="hidden" id="' + emotionTmpContainerId + '"></div>');

        options.tempContainer = $('#' + emotionTmpContainerId);

        // 取表情包列表
        mccmsa.ajax({
            url: '/syFace/retrieveFacePkgList',
            success: function(pkgData){
                if(pkgData.status == 300){
                    return;
                }

                // 取第一个表情包的表情
                mccmsa.ajax({
                    url: '/syFace/retrieveFaceInfoList',
                    data: {
                        id: pkgData.result.resultList[0].id
                    },
                    success: function(faceData){
                        if(faceData.status == 300){
                            return;
                        }

                        // 默认显示第一个表情包的表情，将一个表情包表情塞进pkgData进行初次显示
                        pkgData.result.resultList[0].emotions = faceData.result.resultList;

                        mccmsa.getHtmlFromRemoteTemplate({
                            templateName: 'emotionPanel',
                            container: options.tempContainer,
                            data: pkgData.result,
                            callback: function(){
                                //$.Huitab("#tab_demo .tabBar span","#tab_demo .tabCon","current","click","0");

                            }
                        });
                    }
                });

            }
        });
    }

    var backgroundCoverEle = $('#emotion-background-cover');
    backgroundCoverEle.on('click', function(){
        backgroundCoverEle.addClass('hidden');

        options.panelRelativeTo.children('.emotion').remove();
        self.attr('opened', 0);
    });

    return this.each(function(){
        var self = $(this).attr('opened', '0');

        self.on('click', function(event){
            event.stopPropagation();

            if(self.attr('opened') == 0){
                options.panelRelativeTo.append(options.tempContainer.html());
                $.EmotionHuitab("#tab_demo .tabBar span","#tab_demo .tabCon","current","click","0", function(){
                    var currentTab = $(this);
                    var tabIndex = currentTab.parent().children().index(currentTab);
                    var tabContent = $('#tab_demo .tabCon').eq(tabIndex).find('.emotion__tab-content_emotion-wrapper');

                    // 还没有查看过的才请求表情数据显示
                    if(tabContent.children().length <= 0){
                        getFaceByPackageId(currentTab.attr('packageid')).then(function(result){

                            var template = Handlebars.compile(emtionTemplate);
                            tabContent.html(template(result));

                        });
                    }

                });

                options.panelRelativeTo.off().on('click', '.emotion__tab-content__emotion-image', function(){
                    var emotionImage = $(this);

                    options.inputElement.val(options.inputElement.val() + emotionImage.attr('code'));

                    options.panelRelativeTo.children('.emotion').remove();
                    self.attr('opened', 0);

                    backgroundCoverEle.addClass('hidden');
                });

                self.attr('opened', 1);

                backgroundCoverEle.removeClass('hidden');

            }else{
                options.panelRelativeTo.children('.emotion').remove();
                self.attr('opened', 0);

                backgroundCoverEle.addClass('hidden');
            }
        });
    });

    function getFaceByPackageId(packageId){
        var def = $.Deferred();
        var storageItemKey = 'package-emotions-' + packageId;

        if(!sessionStorage.getItem(storageItemKey)){
            mccmsa.ajax({
                url: '/syFace/retrieveFaceInfoList',
                data: {
                    id: packageId
                },
                success: function(data){
                    sessionStorage.setItem(storageItemKey, JSON.stringify(data.result));

                    def.resolve(data.result);
                }
            });
        }else{
            def.resolve(JSON.parse(sessionStorage.getItem(storageItemKey)));
        }

        return def;
    }
};
/* Jquery plugin END 